var jwt = require('jsonwebtoken');
const db = require("../config/environment.json"); //引入数据库封装模块

const SECRET_KEY = db.JWT_SECRET || 'TEST';
const ACCESS_TOKEN_EXPIRES_IN_MS = db.ACCESS_TOKEN_EXPIRES_IN_MS || 30 * 60
const REFRESH_TOKEN_EXPIRES_IN_MS = db.REFRESH_TOKEN_EXPIRES_IN_MS || 24 * 60 * 60


const tokenTools = {
  // 添加JWT验证中间件
  authenticate: (req, res, next) => {
    const authHeader = req.headers['authorization'];
    if (authHeader) {
      const token = authHeader.split(' ')[1]; // 假设bearer模式 Authorization: Bearer <token>
      try {
        const decoded = jwt.verify(token, SECRET_KEY);
        req.user = decoded;
        next();
      } catch (error) {
        if (error instanceof jwt.TokenExpiredError) {
          res.status(401).json({ returncode: 104, info: "token过期" });
        } else {
          res.status(401).json({ returncode: 104, info: "无效的token" });
        }
      }
    } else {
      res.status(401).json({ returncode: 104, info: "缺少token" });
    }
  },

  // 定义生成 Access Token 的函数
  generateAccessToken: (userId) => {
    return jwt.sign({ userId }, SECRET_KEY, { noTimestamp: true,  expiresIn: ACCESS_TOKEN_EXPIRES_IN_MS });
  },
  
  // 定义生成 Refresh Token 的函数
  generateRefreshToken: (userId) => {
    return jwt.sign({ userId, purpose: 'refresh' }, SECRET_KEY, { noTimestamp: true, expiresIn: REFRESH_TOKEN_EXPIRES_IN_MS });
  }
}

module.exports = tokenTools

